package DEMO;
//在类中单独定义一-个对象lo_ker作为锁对象
public class demo_8 {
    public static void main(String[] args) throws InterruptedException {
        Counter8 counter = new Counter8();
        Counter8 counter1=new Counter8();
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 5_0000; i++) {
                counter.increase();
            }
        });
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 5_0000; i++) {
                counter1.increase();
            }
        });
        //启动线程
        thread1.start();
        thread2.start();
        //等待线程执行完成
        thread1.join();
        thread2.join();
        //打印结果
        System.out.println("count= " + counter.count);
    }
}
//创建一个类用来累加
class Counter8{
    public static int count=0;
    static Object lo_ker=new Object();
    //用synchronized 锁住整个方法
    public void increase(){
        synchronized(lo_ker){
            count++;
        }
    }
}